<script setup>
import Toolbar from '@/components/Toolbar.vue';
import { useRoute } from 'vue-router';
import { useUserStore } from '@/stores/userStore';
import { getButtonList } from "@/utils/index";
import { onMounted, ref } from 'vue';
import { getDataList,addDate, editDate, delDate } from '@/apis/permission';
import { ElMessage, ElMessageBox } from "element-plus";
import {getPermissionTree} from '@/apis/permission'
import { getModuleListPage } from '@/apis/module';

const route = useRoute();
const userStore = useUserStore();
// 当前登录用户拥有的按钮列表
const buttonList = getButtonList(route.path, userStore.userMenuPermissions);

// 用户列表
const userList = ref([]);
// 请求数据列表参数
const parms = ref({
  page: 0,
  pageSize: 5,
  currentPage: 1,
  total: 0,
  parentId:0,
  key: "",
});
const tableRef = ref(null)
// 获取用户列表
const getRoles = async () => {
  console.log(parms.value)
  const res = await getDataList(parms.value);
  // parms.value.total = res.dataCount;
  userList.value = res;
};

const getPermissionTreeData = async()=>{
  options.value=[]
  const res = await getPermissionTree(parms.value)
  isResouceShow.value++
  // console.log(res)
  options.value.push(res)
}
// 展开列表菜单加载下级节点
const load = async(tree, treeNode, resolve)=>{
  parms.value.parentId = tree.id
  const res = await getDataList(parms.value);
  resolve(res);
}

const getModuleData = async()=>{
  const res = await getModuleListPage({page:-1})
  // console.log(res)
  modules.value = res.data
}
onMounted(()=>{
  getRoles()
  // getPermissionTreeData()
  getModuleData()
})
// 显示添加弹框标记
const showDialogForm = ref(false);
// 当前选择行
const currentRow = ref(null);
const isEdit = ref(false)

const selectRow = (selection, row) => {
  console.log(selection, row);
  currentRow.value = null;
  tableRef.value.clearSelection();
  if (selection.length == 0) {
    return;
  }
  if (row) selectCurrentRow(row);
};
// 点击行勾选复选框
const selectCurrentRow = (val) => {
  // console.log(val);
  currentRow.value = val;
  tableRef.value.clearSelection();
  tableRef.value.toggleRowSelection(val, true);
};
// 点击按钮事件
const buttonClick = (item) => {
   console.log(item);
  parms.value.key = item.search;
  if (item.func == "handleAdd") {
    isEdit.value = false;
    handleAdd();
  } else if (item.func == "handleEdit") {
    handleEdit();
    isEdit.value = true;
  } else if (item.func == "handleDel") {
    handleDelete();
  } else if (item.func == "getPermissions") {
    getRoles();
  }
};
// 添加/编辑表单数据
let dialogForm = ref({
  id: 0,
  name:'',
  menuType:'',
  code:'',
  description:'',
  enabled:true,
  orderSort:0,
  isButton:false,
  func:'',
  isHide:false,
  isKeepAlive:false,
  pidArr:[],
  mid:0,
});
const rules = ref({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  code: [{ required: true, message: "请选添加路由", trigger: "blur" }],
});
// 点击添加按钮弹框form表单
const handleAdd = async () => {
  dialogForm.value = {
    id: 0,
    name:'',
    menuType:'',
    code:'',
    description:'',
    enabled:true,
    orderSort:0,
    isButton:true,
    func:'',
    isHide:false,
    isKeepAlive:false,
    pidArr:[],
    mid:0,
  };
  await getPermissionTreeData()
  showDialogForm.value = true;
};

// 编辑弹框
const handleEdit = async () => {
  if (currentRow.value) {
    // parms.value.parentId = currentRow.value.id
    await getPermissionTreeData()
    dialogForm.value = Object.assign({}, currentRow.value);
    // console.log(dialogForm.value)
    showDialogForm.value = true;
  } else {
    ElMessage.warning("请选择要编辑的数据");
  }
};

// form引用
const ruleFormRef = ref(null);
// 提交表单
const submitForm = () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let formValue = dialogForm.value
      formValue.pid=formValue.pidArr.pop()
      let msg = "添加成功";
      if (isEdit.value) {
        await editDate(formValue);
        msg = "编辑成功";
      } else {
        await addDate(formValue);
      }
      ElMessage.success(msg);
      parms.value.page = 0;
      // parms.value.currentPage = 1;
      getRoles();
      resetForm();
    } else {
      console.error("error submit", fields);
    }
  });
};

// 取消表单
const resetForm = () => {
  showDialogForm.value = false;
  ruleFormRef.value.clearValidate();
  ruleFormRef.value.resetFields();
};

// 删除
const handleDelete = async () => {
  if (currentRow.value) {
    ElMessageBox.confirm("确定要删除吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        await delDate({ id: currentRow.value.id });
        ElMessage.success("删除成功");
        getRoles();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "Delete canceled",
        });
      });
  } else {
    ElMessage.warning("请选择要编辑的数据");
  }
};

// // 分页改变
// const handleCurrentChange = (page) => {
//   // console.log(page);
//   parms.value.page = page;
//   parms.value.currentPage = page;
//   getRoles()
// };

const options = ref([])
const modules = ref([])
const editLoading = ref(false)
const isResouceShow = ref(0)

</script>

<template>
  <toolbar :button-list="buttonList" @call-function="buttonClick"></toolbar>

  <el-table :data="userList" :load="load" @select="selectRow" @row-click="selectCurrentRow" border ref="tableRef" row-key="id" lazy
            :tree-props="{children:'children',hasChildren:'hasChildren'}">
    <el-table-column type="selection" width="50"></el-table-column>
    <el-table-column type="index" width="80" label="序号"></el-table-column>
    <el-table-column prop="name" label="菜单/按钮" sortable>
      <template #default="{row}">
        <el-icon>
          <component :is="row.icon" />
        </el-icon>
        {{ row.name }}
      </template>
    </el-table-column>
    <el-table-column prop="code" label="路由地址" sortable></el-table-column>
    <el-table-column prop="mName" label="API接口" sortable></el-table-column>
    <el-table-column prop="orderSort" label="Sort" sortable></el-table-column>
    <el-table-column prop="isButton" label="是否按钮" sortable>
      <template #default="{ row }">
        <el-tag :type="row.isButton ? 'success' : 'danger'">
          {{ row.isButton ? "是" : "否" }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="func" label="按钮事件" sortable></el-table-column>
    <el-table-column prop="isHide" label="是否隐藏" sortable>
      <template #default="{ row }">
        <el-tag :type="row.isHide ? 'success' : 'danger'">
          {{ row.isHide ? "是" : "否" }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="isKeepAlive" label="KeepAlive" sortable> <template #default="{ row }">
        <el-tag :type="row.isKeepAlive ? 'success' : 'danger'">
          {{ row.isKeepAlive? "是" : "否" }}
        </el-tag>
      </template></el-table-column>
  </el-table>

  <!-- <el-col :span="24" class="toolbar">
    <el-pagination background layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="parms.pageSize" :total="parms.total"
                   :current-page="parms.currentPage" style="float: right">
    </el-pagination>
  </el-col> -->

  <el-dialog v-model="showDialogForm" :title="isEdit == true ? '编辑菜单/按钮' : '添加菜单/按钮'" :close-on-click-modal="false" @close="resetForm">
    <el-form ref="ruleFormRef" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon :model="dialogForm">
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="dialogForm.name" />
      </el-form-item>
      <el-form-item label="菜单类型" prop="menuType">
        <el-radio-group v-model="dialogForm.menuType">
          <el-radio value="0">目录</el-radio>
          <el-radio value="1">页面</el-radio>
          <el-radio value="2">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="路由地址" prop="code">
        <el-tooltip placement="top" effect="customized">
          <template v-slot:content>
            如果是目录，请填‘-’字符
            <br />如果是按钮，请输入空格即可
            <br />如果是外链，请带上协议，比如 https://www.baidu.com
            <br />
          </template>
          <el-input v-model="dialogForm.code" autocomplete="off"></el-input>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="dialogForm.description" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-select v-model="dialogForm.enabled" placeholder="请选择状态">
          <el-option :value="true" label="激活"></el-option>
          <el-option :value="false" label="禁用"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="orderSort">
        <el-input v-model="dialogForm.orderSort" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="是否按钮" prop="isButton">
        <el-switch v-model="dialogForm.isButton"></el-switch>
      </el-form-item>
      <el-form-item label="按钮事件" prop="func">
        <el-tooltip content="只写方法名即可，不用带括号，比如：handleEdit" placement="top">
          <el-input v-model="dialogForm.func" autocomplete="off"></el-input>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="隐藏菜单" prop="isHide">
        <el-switch v-model="dialogForm.isHide"></el-switch>
      </el-form-item>
      <el-form-item label="KeepAlive" prop="isKeepAlive">
        <el-switch v-model="dialogForm.isKeepAlive"></el-switch>
      </el-form-item>
      <el-form-item label="父级菜单" prop="pidArr">
        <el-cascader v-model="dialogForm.pidArr" :options="options" filterable :key="isResouceShow" v-if="!editLoading" style="width: 100%"
                     :props="{ checkStrictly: true, expandTrigger: 'hover' }" />
        <el-cascader placeholder="加载中..." style="width: 100%" v-if="editLoading"></el-cascader>
      </el-form-item>
      <el-form-item prop="mid" label="Api接口">
        <el-select style="width:100%" v-model="dialogForm.mid" placeholder="请选择API">
          <el-option :key="0" :value="0" :label="'无需api'"></el-option>
          <el-option v-for="item in modules" :key="item.id" :value="item.id" :label="item.linkUrl">
            <span style="float:left">{{ item.linkUrl }}</span>
            <span style="float:right;color:#8492a6;font-size: 13px;">{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
  .el-popper__arrow::before {
    background: linear-gradient(45deg, #b2e68d, #bce689);
    right: 0;
  }
}
</style>